//
//  CalculatorAppViewController.m
//  CalculatorApp
//
//  Created by Michael Geering on 26/02/2010.
//  Copyright SDC 2010. All rights reserved.
//


#import "CalculatorAppViewController.h"
#import "CalculatorAppAppDelegate.h"


#define CONTEMPT_LEVEL 4;
#define RANDOM_LEVEL 10;


@implementation CalculatorAppViewController

@synthesize button1, button2, button3, button4, button5, button6, button7, button8, button9, button0,
buttonMinus, buttonMultiply, buttonDivide, buttonPlus, calcDisplay, buttonEquals, buttonClear,
buttonRand, buttonPosNeg, xCoordArray, yCoordArray, buttonIdentityRemain, buttonIdentity, buttonDecimal,
xCoordRemain, yCoordRemain, snarkyMessages, modifier, brokenView, brokenImage;


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	
	// Arrays for storing the x and y coordinates of all movable buttons.
	// Stored in order from top-left to bottom-right.
	// Does not include large buttons such as equals.
	
	[self setModifier:[[NSArray alloc] initWithObjects:@"+",@"-",@"/",@"*",nil]];
	[self setXCoordArray:[[NSArray alloc] initWithObjects:@"8", @"86", @"164", @"242", @"8", @"86", @"164", @"242", 
						  @"8", @"86", @"164", @"242", @"8", @"86", @"164", @"164", nil]];
	[self setYCoordArray:[[NSArray alloc] initWithObjects:@"86", @"86", @"86", @"86", @"164", @"164", @"164", 
						  @"164", @"242", @"242", @"242", @"242", @"320", @"320", @"320", @"398", nil]];
	[self setButtonIdentity:[[NSArray alloc] initWithObjects:buttonClear, buttonPosNeg, buttonDivide, 
							 buttonMultiply, button7, button8, button9, buttonMinus, button4, 
							 button5, button6, buttonPlus, button1, button2, 
							 button3, buttonDecimal, nil]];
	[self setButtonIdentityRemain:[[NSMutableArray alloc] initWithArray:[self buttonIdentity]]];
	[self setXCoordRemain:[[NSMutableArray alloc] initWithArray:[self xCoordArray]]];
	[self setYCoordRemain:[[NSMutableArray alloc] initWithArray:[self yCoordArray]]];
	
	self.snarkyMessages = [[NSArray alloc] initWithObjects:
						   @"You had to get a calculator out for that?",
						   @"Here I am, brain the size of a planet, and they ask me to do this?!",
						   @"Don't insult my intelligence!",
						   @"Do it yourself.  Stupid ape.",
						   @"Oy, fleshbag!  Try counting on your fingers!",
						   @"Is *that* really worth bothering me?  I ask you.",
						   @"Kids these days... don't they teach you to count in those schools of yours?",
						   nil];
	
	
	//Accelerometer Code
	
	UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];
	accel.delegate = self;
	accel.updateInterval = kUpdateInterval;
	self.brokenImage = [UIImage imageNamed:@"crack3.png"];
	screenBroken = NO;
	
	//Used for defining whether the decimal button has been pressed.
	decimalUsed = NO;
	
	kRandomValue = CONTEMPT_LEVEL;
	kMessageValue = RANDOM_LEVEL;
	
	currentButton = 0;
	previousButton = 0;
	
	srandom(time(NULL));
	
    [super viewDidLoad];

}

- (NSString *) getSnarkyMessage {
	int messageCount = [snarkyMessages count];
	return [snarkyMessages objectAtIndex:random() % messageCount];
}

- (IBAction)PressedNum:(id)sender{
	currentButton = decimalUsed
	  ? currentButton + [[sender currentTitle] intValue] / (10 * pow(10, numDecimal++))
	  : currentButton * 10 + [[sender currentTitle] intValue];
	
	[calcDisplay setText:[NSString stringWithFormat:@"%f", currentButton]];
	
	pressCount += 1;
	
	[self PressedRand];
}

- (IBAction)PressedOperator:(id)sender {
	currentModifier = [modifier indexOfObject:[sender currentTitle]] + 1;
	previousButton = currentButton;
	currentButton = numDecimal = 0;
	decimalUsed = NO;
	pressCount += 1;
	[self PressedRand];
}

- (IBAction)PressedClear:(id)sender {
	currentButton = currentModifier = previousButton = numDecimal = 0;
	decimalUsed = NO;
	pressCount += 1;
	[calcDisplay setText:[NSString stringWithFormat:@"0"]];
	[self PressedRand];
}

- (IBAction)PressedPosNeg:(id)sender {
	[calcDisplay setText:[NSString stringWithFormat:@"%f", currentButton = -currentButton]];
	++pressCount;
	[self PressedRand];
}
- (IBAction)PressedDecimal:(id)sender {
	if (decimalUsed) return;
	
	decimalUsed = YES;
	numDecimal = 0;
	[calcDisplay setText:[NSString stringWithFormat:@"%f.", currentButton]];
}
- (IBAction)equalsPressed:(id)sender {
	int difficulty = 12 - kMessageValue;
	
	if ((random() % difficulty) < 1 && messageButtonState) {
		UIAlertView *alert = [[UIAlertView alloc]
							  initWithTitle:@"Excuse Me!"
							  message: [self getSnarkyMessage]
							  delegate:self
							  cancelButtonTitle:@"Alright!"
							  otherButtonTitles:nil];
		
		[alert show];
		[alert release];
		previousButton = currentButton;
		currentButton = 0;
		[calcDisplay setText:@"0"];
	} else {
		switch (currentModifier)
		{
			case 1:
				[calcDisplay setText:[NSString stringWithFormat:@"%f",
									  currentButton = previousButton + currentButton]];
				break;
				
			case 2:
				[calcDisplay setText:[NSString stringWithFormat:@"%f",
									  currentButton = previousButton - currentButton]];
				break;
				
			case 3:
				if (currentButton == 0) // Checks for dividing by zero.
					[calcDisplay setText:@"0"];
				else	
					[calcDisplay setText:[NSString stringWithFormat:@"%f",
										  currentButton = previousButton / currentButton]];
				break;
				
			case 4:
				[calcDisplay setText:[NSString stringWithFormat:@"%f",
									 currentButton = previousButton	* currentButton]];
				break;
				
				
			default:
				[calcDisplay setText:[NSString stringWithFormat:@"%f", currentButton]];
		}
	}
	previousModifier = currentModifier;
	currentModifier = 0;
	previousButton = currentButton;
	currentButton = 0;
	decimalUsed = NO;
	numDecimal = 0;
	pressCount += 1;
	[self PressedRand];
}

- (IBAction)PressedRand {
	if (!randomButtonState) {
		pressCount = 0;
		return;
	}
	int i, a, b, randChance, randUpper, randLower;
	UIButton *selectedButton; //Generic placeholder for a button object.
	randUpper = kRandomValue * 6/5;
	randLower = kRandomValue * 4/5;
	randChance = randLower + random() %(randUpper - randLower);
		
	if (pressCount > randChance) {
		while (i = [buttonIdentityRemain count]) {
			a = random() % [buttonIdentityRemain count];
			b = random() % [buttonIdentityRemain count];
			
			//Sets the frame for the placeholder (and hence the button it represents) to a random x,y from the respective arrays.
			selectedButton = [buttonIdentityRemain objectAtIndex:b];
			selectedButton.frame = CGRectMake([[xCoordRemain objectAtIndex:a] doubleValue],
											  [[yCoordRemain objectAtIndex:a] doubleValue],
											  70, 70);
			
			//Removes the button, and the x,y coordinates from their arrays so can't be used again.
			[buttonIdentityRemain removeObjectAtIndex:b];
			[xCoordRemain removeObjectAtIndex:a];
			[yCoordRemain removeObjectAtIndex:a];
			
		}
		
		//Removes all objects from the arrays, then re-adds the objects from the immutable arrays, for the next button press.
		[buttonIdentityRemain removeAllObjects];
		[xCoordRemain removeAllObjects];
		[yCoordRemain removeAllObjects];
		
		[buttonIdentityRemain addObjectsFromArray:buttonIdentity];
		[xCoordRemain addObjectsFromArray:xCoordArray];
		[yCoordRemain addObjectsFromArray:yCoordArray];
		
		pressCount = 0;

	}
	
}

-(void)settingsViewControllerDidFinish:(SettingsViewController *)controller {
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)showSettings {
	SettingsViewController *controller = [[SettingsViewController alloc] initWithNibName:@"SettingsViewController" bundle:nil];
	controller.delegate = self;
	
	controller.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
	[self presentModalViewController:controller animated:YES];
	
	[controller release];
}



- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	
	button0
	= button1
	= button2
	= button3
	= button4
	= button5
	= button6
	= button7
	= button8
	= button9
	= buttonPlus
	= buttonDivide
	= buttonMinus
	= buttonMultiply
	= buttonEquals
	= buttonClear
	= buttonPosNeg
	= buttonRand
	= self.brokenView
	= self.brokenImage
	= self.xCoordArray
	= self.yCoordArray
	= self.buttonIdentity
	= self.buttonIdentityRemain
	= self.xCoordRemain
	= self.yCoordRemain = nil;
	
	
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc {
	for (int i = 0, n = [buttonIdentity count]; i < n; ++i)
		[[self.buttonIdentity objectAtIndex:i] release];
	
	[buttonRand release];
	[xCoordArray release];
	[yCoordArray release];
	[buttonIdentity release];
	[yCoordRemain release];
	[xCoordRemain release];
	[buttonIdentityRemain release];
	[brokenView release];
	[brokenImage release];
	
    [super dealloc];
}

#pragma mark -
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
	if (acceleration.x <= kAccelerationThreshold &&
		acceleration.y <= kAccelerationThreshold &&
		acceleration.z <= kAccelerationThreshold)
		return;
	
	brokenView.hidden = !brokenView.hidden;
	screenBroken = !screenBroken;
	
	if (!screenBroken)
		brokenView.image = brokenImage;
}

@end

